package com.ali.Reggie.service.impl;

import com.ali.Reggie.common.BaseContext;
import com.ali.Reggie.common.CustomException;
import com.ali.Reggie.entity.AddressBook;
import com.ali.Reggie.entity.OrderDetail;
import com.ali.Reggie.entity.Orders;
import com.ali.Reggie.entity.ShoppingCart;
import com.ali.Reggie.entity.User;
import com.ali.Reggie.mapper.AddressBookMapper;
import com.ali.Reggie.mapper.OrdersMapper;
import com.ali.Reggie.service.AddressBookService;
import com.ali.Reggie.service.OrderDetailService;
import com.ali.Reggie.service.OrdersService;
import com.ali.Reggie.service.ShoppingCartService;
import com.ali.Reggie.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：ALi
 * @date ：Created in 2022/6/15 10:40
 * @description：订单类实现类
 * @modified By：
 * @version: $
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    //用户下单
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获得用户id
        Long userID = BaseContext.getCurrentID();

        //得到购物车中订单内容
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userID);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

            //得到用户信息
        User userInfo = userService.getById(userID);
            //查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //订单号
        long orderId = IdWorker.getId();
        //  购物车中 商品 的总金额 需要保证在多线程的情况下 也是能计算正确的，故需要使用原子类
        AtomicInteger amount = new AtomicInteger(0);
        //设置ordersDetail的属性
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (ShoppingCart shoppingCart:shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }

        //设置orders的属性
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额，需要 遍历购物车，计算相关金额来得到
        orders.setUserId(userID);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(userInfo.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));


        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(lambdaQueryWrapper);
    }
}